package rbac

import (
	"encoding/gob"
	//"log"
	"time"

	. "xwaf_admin/xadmin/src"
	admlib "xwaf_admin/xadmin/src/lib"
	m "xwaf_admin/xadmin/src/models"

	"github.com/beego/beego/v2/client/cache"
	//"github.com/beego/beego/v2/client/orm"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/captcha"
	//"github.com/tidwall/gjson"
)

type MainController struct {
	CommonController
}

type Tree struct {
	Id         int64      `json:"id"`
	Text       string     `json:"text"`
	IconCls    string     `json:"iconCls"`
	Sorts      int64      `json:"sorts"`
	Checked    string     `json:"checked"`
	State      string     `json:"state"`
	Children   []Tree     `json:"children"`
	Attributes Attributes `json:"attributes"`
}
type Attributes struct {
	Url   string `json:"url"`
	Price int64  `json:"price"`
}

var cpt *captcha.Captcha

func init() {
	store := cache.NewMemoryCache()
	cpt = captcha.NewWithFilter("/public/captcha/", store) //一定要写在构造函数里面，要不然第一次打开页面有可能是X
	// 设置验证码长度
	cpt.ChallengeNums = 5
	// 设置验证码模板高度
	cpt.StdHeight = 40
	// 设置验证码模板宽度
	cpt.StdWidth = 120

	gob.Register(m.User{})
}

//后台首页
func (this *MainController) Index() {
	userinfo := this.GetSession("userinfo")
	if userinfo == nil {
		authGateWay, _ := beego.AppConfig.String("rbac_auth_gateway")
		this.Ctx.Redirect(302, authGateWay)
		return
	}
	this.Data["userinfo"] = userinfo
	this.TplName = "front/xwaf_index.html"
}

//登录
func (this *MainController) Login() {
	isajax := this.GetString("isajax")
	// log.Println(string(this.Ctx.Input.RequestBody))
	if isajax == "1" {
		username := this.GetString("username")
		password := this.GetString("password")
		user, err := CheckLogin(username, password)
		if err == nil {
			this.SetSession("userinfo", user)
			accesslist, _ := GetAccessList(user.Id)
			this.SetSession("accesslist", accesslist)
			//log record start
			userip := this.Ctx.Request.RemoteAddr
			admlib.SecurityLog(userip, username, "AdmLogin", "-")
			//log record end
			logintime := time.Now().Format("2006-01-02T15:04:05")
			m.UpdateLoginIpTime(user.Id, logintime, userip)
			this.Rsp(true, "登录成功")
			return
		} else {
			this.Rsp(false, err.Error())
			return
		}
	}

	userinfo := this.GetSession("userinfo")
	if userinfo != nil {
		this.Ctx.Redirect(302, "/index")
	}
	//this.TplName = this.GetTemplatetype() + "/public/login.tpl"
	this.TplName = this.GetTemplatetype() + "/login.html"
}

//退出
func (this *MainController) Logout() {
	this.DelSession("userinfo")
	this.Ctx.Redirect(302, "/login.html")
}

//修改密码
func (this *MainController) Changepwd() {
	userinfo := this.GetSession("userinfo")
	if userinfo == nil {
		authGateway, _ := beego.AppConfig.String("rbac_auth_gateway")
		this.Ctx.Redirect(302, authGateway)
	}
	if this.IsAjax() {
		oldpassword := this.GetString("oldpassword")
		newpassword := this.GetString("newpassword")
		repeatpassword := this.GetString("repeatpassword")
		if newpassword != repeatpassword {
			this.Rsp(false, "两次输入密码不一致")
		}
		user, err := CheckLogin(userinfo.(m.User).Username, oldpassword)
		if err == nil {
			var u m.User
			u.Id = user.Id
			u.Password = newpassword
			id, err := m.UpdateUser(&u)
			if err == nil && id > 0 {
				this.Rsp(true, "密码修改成功")
				return
			} else {
				this.Rsp(false, err.Error())
				return
			}
		}
		this.Rsp(false, "密码有误")
	}
}

//个人信息
func (this *MainController) MyInfo() {
	userinfo := this.GetSession("userinfo")
	if userinfo == nil {
		authGateway, _ := beego.AppConfig.String("rbac_auth_gateway")
		this.Ctx.Redirect(302, authGateway)
	}
	if this.IsAjax() {
		user := m.GetUserById(userinfo.(m.User).Id)
		this.Data["json"] = &map[string]interface{}{"data": &user}
		this.ServeJSON()
	} else {
		this.TplName = this.GetTemplatetype() + "/myinfo.html"
	}
}
